﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Linq;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinPreferences.xaml 的交互逻辑
    /// </summary>
    public partial class WinPreferences : Window
    {
        public WinPreferences()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (ui_Portrait.SelectedIndex)
            {
                case 0: // 烧烤团子
                    ui_PortraitPreview.Source = Imaging.CreateBitmapSourceFromHBitmap(
                        Properties.Resources.Portrait_02.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    break;
                case 1: // 豆沙团子
                    ui_PortraitPreview.Source = Imaging.CreateBitmapSourceFromHBitmap(
                        Properties.Resources.Portrait_01.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    break;
                case 2: // 团子大家族
                    ui_PortraitPreview.Source = Imaging.CreateBitmapSourceFromHBitmap(
                        Properties.Resources.Portrait_03.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    break;
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        public void CannotCloseWindow()
        {
            btn_Close.IsEnabled = false;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 初始化所有设置的值
            txt_Nickname.Text = Data.PersonalInfo.Nickname;
            txt_Email.Text = Data.PersonalInfo.EmailAddress;
            txt_TelNumber.Text = Data.PersonalInfo.TelNumber;
            if (Data.PersonalInfo.Portrait != 0)
            {
                ui_Portrait.SelectedIndex = Data.PersonalInfo.Portrait;
            }

            txt_Port.Text = GlobalConfig.ListeningPort.ToString();
            //txt_ServerIp.Text = GlobalConfig.ServerHost;
            //txt_ServerPort.Text = GlobalConfig.ServerPort.ToString();
        }

        private void btn_Ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 检查数据的有效性
                if (txt_Nickname.Text.Trim() == "")
                {
                    throw new FormatException("必须填入一个昵称");
                }
                Regex emailCheck = new Regex(@"(?<name>\S+)@(?<domain>\S+)");
                if (!emailCheck.Match(txt_Email.Text.Trim()).Success)
                {
                    throw new FormatException("电子邮件地址格式不正确");
                }
                // 暂时不判断电话号码的有效性

                int inputedPort = GlobalConfig.ListeningPort;
                if (!int.TryParse(txt_Port.Text.Trim(), out inputedPort))
                {
                    throw new FormatException("端口号填写不正确");
                }
                GlobalConfig.ListeningPort = inputedPort;

                XElement newPersonInfo = new XElement("PersonalInfo",
                    new XAttribute("GUID", Data.PersonalInfo.UserId.ToString()),
                    new XAttribute("RegEmail", Data.PersonalInfo.RegEmail),
                    new XElement("Nickname", txt_Nickname.Text.Trim()),
                    new XElement("EmailAddress", txt_Email.Text.Trim()),
                    new XElement("TelNumber", txt_TelNumber.Text.Trim()),
                    new XElement("Portrait", ui_Portrait.SelectedIndex.ToString())
                    );

                // 向服务器提交修改请求
                MemoryStream ms = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, new P2PChat.Data.NetPacket()
                {
                    Tag = P2PChat.Data.PacketTag.ApplyPersonalInfo,
                    Content = new P2PChat.Data.Packets.ApplyPersonalInfoPacket()
                    {
                        NewPersonalInfo = newPersonInfo,
                    },
                });

                using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
                {
                    client.Connect(GlobalConfig.ServerHost, GlobalConfig.ServerPort);
                    client.Client.Send(ms.GetBuffer());

                    P2PChat.Data.NetPacket recvPacket =
                        bf.Deserialize(client.GetStream()) as P2PChat.Data.NetPacket;
                    if (recvPacket.Tag == P2PChat.Data.PacketTag.ApplyPersonalInfo)
                    {
                        if ((recvPacket.Content as P2PChat.Data.Packets.RawStringPacket).Content == "SUCCESS")
                        {
                            Data.PersonalInfo.Parse(newPersonInfo);
                            this.Close();
                        }
                        else
                        {
                            throw new Exception((recvPacket.Content as P2PChat.Data.Packets.RawStringPacket).Content);
                        }
                    }
                    else if (recvPacket.Tag == P2PChat.Data.PacketTag.ServerException)
                    {
                        throw new Exception("服务器端出现了处理异常!过程中断!");
                    }
                    else
                    {
                        throw new Exception("服务器发送的数据无法识别!");
                    }
                }
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败:" + ex.Message);
            }
        }
    }
}
